# -*- coding: utf-8 -*-
"""
Created on Tue Aug 21 14:19:35 2018

@author: Who
牛牛财经
https://niuniu.im/

"""

import requests
import re
from WriteData import writedata
from Tk import genearteMD5


def get_html_text(url, data):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.post(url, timeout=30, data=data, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return None


def get_dates_Kx():
    a = 1
    dates = []
    while a < 180:
        data = {
            'action': 'wpcom_load_kuaixun',
            'page': a,
        }
        url = 'https://niuniu.im/wp-admin/admin-ajax.php'
        a += 1
        print('----牛牛财经快讯第{}页获取中----'.format(a))
        text = get_html_text(url, data)
        if not text:
            continue
        regex = re.compile(r'<span class="kx-time">([\s\S]*?)</span>')
        dates += re.findall(regex, text)
    return dates


def count_process_one():
    l = []
    a = 0
    dates = get_dates_Kx()
    try:
        while 1:
            if dates[a] < dates[a + 1]:
                l.append(a + 1)
            a += 1
            if len(l) == 3:
                break
        return (len(dates[:l[0]]), len(dates[l[0]:l[1]]), len(dates[l[1]:l[2]]))
    except:
        return (0, 0, 0)


def main():
    u = '牛牛财经'
    t1 = count_process_one()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0], "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
